#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */

#include "thread.h"
#include "socket.h"
#include "appl_thread.h"

#include <stdlib.h>
#include <stdio.h>

extern int threads_num;
extern s_mapTh2Hnd g_mapTh2Hnd[];

pthread_t* thread_create()
{
	pthread_t* ths = (pthread_t*)malloc(sizeof(pthread_t) * (threads_num + 1));

	for(int i = 0; i < threads_num; i++){
		if(g_mapTh2Hnd[i].start_flag){
			pthread_create(ths + i,  NULL, g_mapTh2Hnd[i].thread_Handler, g_mapTh2Hnd[i].arg);
		}
	}

	pthread_create(ths + threads_num,  NULL, thread_cancel,  ths);

	return ths;
}

int thread_wait(pthread_t* ths)
{
	for(int i = 0; i < threads_num + 1; i++){
		pthread_join(ths[i],  NULL);
	}

	return 0;
}

void* thread_cancel(void* ths_)
{
	pthread_t* ths = (pthread_t*)ths_;
	int alive = threads_num;
	while(1){
		for(int i = 0; i < threads_num; i++){
			if(g_mapTh2Hnd[i].thread_quit_flag){
				pthread_cancel(ths[i]);
				alive--;
			}
		}
		if(alive == 0)
			break;
	}

	return 0;
}



#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */




